﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZP.Common;
using ZP.DTO.Common;
using ZP.DTO.ep_honor_title;
using ZP.DTO.ht_honor_title;
using ZP.DTO.ht_type1_title;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;
using Z.EntityFramework.Plus;

namespace ZP.BLL
{
    public class ht_honor_titleService : BaseService<ht_honor_title, int>, Iht_honor_titleService
    {

        public List<ht_honor_titleResultDTO> GetAllEPHonorTitle(int? ht_type)
        {
            var psie = (ZPJ_Entities)_repository.GetDbContext();

            List<ht_honor_titleResultDTO> result = new List<ht_honor_titleResultDTO>();
            var iquery = from ht in psie.ht_honor_title.AsNoTracking()
                         where ht.state == ZPFlagType.YES
                         select ht;
            if(ht_type.HasValue && ht_type.Value > 0)
            {
                iquery = iquery.Where(p => p.ht_type == (byte)ht_type);
            }

            //序列化类型为“System.Data.Entity.DynamicProxies.xxxx”的对象时检测到循环引用。 加上这个就OK了
            psie.Configuration.ProxyCreationEnabled = false;

            result = AutoMapper.Mapper.Map<List<ht_honor_titleResultDTO>>(iquery.ToList());
            return result;
        }

        //public ht_honor_titleService(Iht_honor_titleDAL _ht_honor_titleDAL
        //, Iht_type1_fileDAL _ht_type1_fileDAL
        //, Iht_type1_titleDAL _ht_type1_titleDAL)
        //{
        //    this._repository = _ht_honor_titleDAL;
        //    this._ht_type1_fileDAL = _ht_type1_fileDAL;
        //    this._ht_type1_titleDAL = _ht_type1_titleDAL;
        //}

        public List<EPHonorResultDTO> GetEPHonorList(int ep_id)
        {
            var psie = (ZPJ_Entities)_repository.GetDbContext();

            List<EPHonorResultDTO> result = new List<EPHonorResultDTO>();
            var iquery = from ht in psie.ht_honor_title.AsNoTracking()
                         join eh in psie.ep_ht on new { ht.ht_id, ep_id } equals new { eh.ht_id, eh.ep_id }
                         into eh_join
                         from eh in eh_join.DefaultIfEmpty()
                         where ht.state == ZPFlagType.YES
                         select new EPHonorResultDTO
                         {
                             ht_honor_title = ht,
                             ep_ht = eh,
                         };

            //序列化类型为“System.Data.Entity.DynamicProxies.xxxx”的对象时检测到循环引用。 加上这个就OK了
            psie.Configuration.ProxyCreationEnabled = false;

            result = iquery.ToList();
            return result;
        }

        public PageModel<ht_honor_titleResultDTO> GetHonorTitle(ht_honor_titleSearchDTO dto)
        {
            PageModel<ht_honor_titleResultDTO> result = new PageModel<ht_honor_titleResultDTO>();
            var psie = (ZPJ_Entities)_repository.GetDbContext();

            var iquery = from h in psie.ht_honor_title
                         join h2 in psie.ht_honor_title on h.ht_pid equals h2.ht_id
                         into h2_join
                         from h2 in h2_join.DefaultIfEmpty()
                         where h.state == ZPFlagType.YES
                         select new ht_honor_titleResultDTO
                         {
                             ht_id = h.ht_id,
                             ht_pid = h.ht_pid,
                             ht_title = h.ht_title,
                             ht_type = h.ht_type,
                             ht_sort = h.ht_sort,
                             pid_title = h2.ht_title,
                         };

            if (null != dto)
            {
                if (!string.IsNullOrWhiteSpace(dto.SearchText))
                {
                    iquery = iquery.Where(p => p.ht_title.Contains(dto.SearchText));
                }
                if(dto.ht_type.HasValue && dto.ht_type.Value > 0)
                {
                    iquery = iquery.Where(p => p.ht_type == dto.ht_type);
                }
            }
            result.count = iquery.Count();
            iquery = iquery.OrderBy(m => m.ht_sort).Skip((dto.page - 1) * dto.limit).Take(dto.limit);
            //result.rows = Mapper.Map<List<fz_sys_user>, List<fz_sys_userResultDTO>>(iquery.ToList());
            result.data = iquery.ToList();
            return result;
        }

        public List<EPTitleFileResultDTO> GetTitleFile(int ep_id, int ht_id)
        {
            var psie = (ZPJ_Entities)_repository.GetDbContext();

            List<EPTitleFileResultDTO> result = new List<EPTitleFileResultDTO>();
            var iquery = from tt in psie.ht_type1_title.AsNoTracking()
                         join ht in psie.ht_honor_title on tt.ht_id equals ht.ht_id
                         join eh in psie.ep_ht on ht.ht_id equals eh.ht_id
                         into eh_join
                         from eh in eh_join.DefaultIfEmpty()
                         join tf in psie.ht_type1_file on new { tt.ft_id, eh.ep_id } equals new { tf.ft_id, tf.ep_id }
                         into tf_join
                         from tf in tf_join.DefaultIfEmpty()
                         where tt.ht_id == ht_id && eh.ep_id == ep_id && ht.state == ZPFlagType.YES
                         select new EPTitleFileResultDTO
                         {
                             ht_type1_title = tt,
                             ht_type1_file = tf
                         };

            //序列化类型为“System.Data.Entity.DynamicProxies.xxxx”的对象时检测到循环引用。 加上这个就OK了
            psie.Configuration.ProxyCreationEnabled = false;

            result = iquery.ToList();
            return result;
        }

        /// <summary>
        /// 保存荣誉标题-新增/修改
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="operate">1:重置用户密码</param>
        /// <returns></returns>
        public bool SaveEPHonor(ht_honor_titleOperateDTO dto)
        {
            bool result = false;
            using (var psie = (ZPJ_Entities)_repository.GetDbContext())
            {
                if (0 == dto.ht_id || !dto.ht_id.HasValue)
                {
                    //判断是否已经存在用户账号和员工
                    bool existsCount = psie.ht_honor_title.AsNoTracking().Any(p => p.state == ZPFlagType.YES && p.ht_title == dto.ht_title);
                    if (existsCount)
                    {
                        throw new Exception(TipsMessage.该荣誉标题已存在);
                    }

                    //新增
                    var item = Mapper.Map<ht_honor_titleOperateDTO, ht_honor_title>(dto);
                    item.state = ZPFlagType.YES;
                    _repository.Add(item, false);
                    // 记录日志
                    //this.AddLog(psie, new LogData
                    //{
                    //    CurrentLogType = LogType.ADD,
                    //    LogDetails = "新增用户" + dto.account,
                    //    OpratorName = dto.updater
                    //});
                }
                else
                {
                    ht_honor_title item = _repository.Find(dto.ht_id.Value);

                    //判断是否已经存在用户账号和员工
                    bool existsCount = psie.ht_honor_title.AsNoTracking().Any(p => p.state == ZPFlagType.YES && p.ht_title == dto.ht_title && p.ht_id != dto.ht_id);
                    if (existsCount)
                    {
                        throw new Exception(TipsMessage.该荣誉标题已存在);
                    }
                    item.ht_title = dto.ht_title;
                    item.ht_type = dto.ht_type;
                    item.ht_pid = dto.ht_pid;
                    item.ht_sort = dto.ht_sort;
                    //item = Mapper.Map<ht_honor_title>(dto);
                    //修改
                    //item.state = ZPFlagType.YES;
                    _repository.Update(item, false);

                    // 记录日志
                    //this.AddLog(psie, new LogData
                    //{
                    //    CurrentLogType = LogType.MODIFY,
                    //    LogDetails = "修改用户" + dto.account,
                    //    OpratorName = dto.updater
                    //});
                }
                result = _repository.SaveChanges();
            }
            return result;
        }

        /// <summary>
        /// 删除荣誉标题
        /// </summary>
        /// <returns></returns>
        public bool DeleteEPHonor(List<ht_honor_titleOperateDTO> dto, UserLoginDTO loginUser)
        {
            bool result = false;
            if (dto == null || dto.Count <= 0)
            {
                return result;
            }
            List<int> longIds = dto.Select(i => i.ht_id.Value).ToList();
            //查询角色下是否还存在用户，存在则不能删除
            var entitys = _repository.GetModels(p => longIds.Contains(p.ht_id));

            //删除用户
            //Delete(psie, users);
            int updateCount = entitys.Update(p => new ht_honor_title() { state = ZPFlagType.NO });
            if (updateCount > 0)
            {
                string str_ht_title = string.Join(",", entitys.Select(o => o.ht_title).ToList());
                // 记录日志
                //this.AddLog(psie, new LogData
                //{
                //    CurrentLogType = LogType.DELETE,
                //    LogDetails = "删除用户" + strUserName,
                //    OpratorName = loginUser.account
                //});
            }
            result = updateCount > 0;
            return result;
        }

    }
}
